package org.example.aitest.test;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.example.aitest.dto.DeepseekDto;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class Text {

    private static final Integer TIME_OUT= 5 * 60;

    static final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(TIME_OUT,TimeUnit.SECONDS)
            .writeTimeout(TIME_OUT,TimeUnit.SECONDS)
            .build();

    public static GenerationResult callWithMessage(String address,String query) throws NoApiKeyException, InputRequiredException, IOException {
        Generation gen = new Generation();
        String tools = "[{\"name\":\"get_current_time\"," +
                "\"description\":\"当你想知道现在的时间时非常有用。\"," +
                "\"parameters\":{"+new Date() +"}"+
                "}," +
                "{\"name\":\"get_current_weather\"," +
                "\"description\":\"当你想查询指定城市的天气时非常有用。\","+
                "\"parameters\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"城市或县区，比如北京市、杭州市、余杭区等。\","+getWeather(address)+"}}," +
                "\"required\":[\"location\"]}"+
                "}," +
                "{\"name\":\"get_current_electricity\"," +
                "\"description\":\"当你需要知道一些电力相关内容时非常有用\"," +
                "\"parameters\":{"+getAi(query)+"}" +
                "}" +
                "]";

        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are Qwen, created by Alibaba Cloud. You are a helpful assistant. You may call one or more tools to assist with the user query. " +
                        "The tools you can use are as follows:"+tools+"Response in NORMAL_MODE.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(query)
                .build();

        GenerationParam param = GenerationParam.builder()
                .apiKey("sk-06daae4607c0459295ccd4db313f9719")
                .model("qwen-plus")
//                .incrementalOutput(true) //流式输出时是否以增量输出，默认为false
                .messages(Arrays.asList(systemMsg,userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();

       return gen.call(param); //非流式输出
    }
    public static String getAi(String query){


        MediaType mediaType = MediaType.parse("application/json");

        // 封装请求体参数
        String appId = "03833f43-5395-4368-9f06-4f40f0e74154";
        DeepseekDto deepseekDto = new DeepseekDto();
        deepseekDto.setApp_id(appId);
        deepseekDto.setQuery(query);
        deepseekDto.setConversation_id("c2abc323-6031-49cb-8c59-329fc5a77be2");
        deepseekDto.setStream(true);

        String content1 = JSONObject.toJSONString(deepseekDto);

        RequestBody bodys = RequestBody.create(mediaType, content1);
        Request request1 = new Request.Builder()
                .url("https://qianfan.baidubce.com/v2/app/conversation/runs")
                .post(bodys)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer bce-v3/ALTAK-Wibjv1UyZaOSDCWAMubUA/e1f005de3ccfa2d05a7bf6a5dab040014edf10b3")
                .build();

        if(StringUtils.isEmpty(query)){
            throw new RuntimeException("请输入你想问内容");
        }

        StringBuilder answer = new StringBuilder();

        try (Response response2 = client.newCall(request1).execute()){
            if (response2.isSuccessful()) {
                ResponseBody body1 = response2.body();
                if (body1 != null) {
                    // 使用ResponseBody的source()方法以流的方式处理响应
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(body1.byteStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            // 处理每一行数据
                            if(line.length() > 6) {
                                String substring = line.substring(6);
                                JSONObject jsonObject = JSONObject.parseObject(substring);
                                String answer1 = jsonObject.getString("answer");

                                if(StringUtils.isEmpty(answer1)) {
                                    answer.append(answer1);
                                }
                            }
                        }
                    }
                }

                return answer.toString();
            } else {
                return "失败"+response2.code();
            }
        }catch (IOException e) {
            e.printStackTrace();
            return "错误"+e.getMessage();
        }
    }


    // 查询指定城市天气
    public static String getWeather(String address) throws IOException {
        // 1.获取城市的adcode
        String adcode = getString(address);

        Request request1 = new Request.Builder()
                .url("https://restapi.amap.com/v3/weather/weatherInfo?key=7a801ac3bd571413bfa2ae7538bad391&city="+adcode)
                .build();
        Response execute = client.newCall(request1).execute();
        return execute.body().string();
    }

    private static String getString(String address) throws IOException {
        Request request = new Request.Builder()
                .url("https://restapi.amap.com/v3/geocode/geo?key=7a801ac3bd571413bfa2ae7538bad391&address="+ address)
                .build();
        Response execute1 = client.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(execute1.body().string());
        List<Object> list = (List<Object>) jsonObject.get("geocodes");
        JSONObject jsonObject1 = JSONObject.parseObject(list.get(0).toString());
        String adcode = (String) jsonObject1.get("adcode");
        System.out.println(adcode);
        return adcode;
    }

    public static void main(String[] args) throws NoApiKeyException, InputRequiredException, IOException {
        GenerationResult result = callWithMessage("宜宾","电力安全");
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
    }
}
